<template>
	<el-main style="padding:0 20px;">
		<el-card shadow="never">
		<el-divider content-position="left" >基本信息</el-divider>
		<el-form ref="form" :rules="rules" :model="basicInfo" label-width="100px" style="margin-top: 10px;">
			<el-row :gutter="10">
				<el-col :span="10">
					<el-form-item label="主题" size="default" prop="topic">
						<el-input v-model="basicInfo.topic" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="10">
					<el-form-item label="申请时间" size="default" prop="applyTime"> 
						<el-input v-model="basicInfo.applyTime" readonly></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="10">
				<el-col :span="10">
					<el-form-item label="工号" size="default" prop="jobNumber">
						<el-input v-model="basicInfo.jobNumber" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="10">
					<el-form-item label="姓名" size="default" prop="username">
						<el-input v-model="basicInfo.name" readonly></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="10">
				<el-col :span="10">
					<el-form-item label="地区" size="default" prop="place">
						<el-input v-model="basicInfo.place" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="10">
					<el-form-item label="工厂(部门)" size="default" prop="factory">
						<el-input v-model="basicInfo.factory" readonly></el-input>
					</el-form-item>
				</el-col>
			</el-row>
				<el-row :gutter="10">
					<el-col :span="10">
						<el-form-item label="部门(科室)" size="default" prop=department>
							<el-input v-model="basicInfo.department" readonly></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="10">
						<el-form-item label="邮箱" size="default" prop="email">
							<el-input v-model="basicInfo.email" readonly></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<el-col :span="20">
						<el-form-item label="申请原因" size="default" prop="applyReason">
							<el-input v-model.trim="basicInfo.applyReason" type="textarea" :readonly="normalState || pageType!=2"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<el-col :span="10" v-if="!normalState && pageType == 2">
						<el-form-item label="审核人" size="large">
							<el-input v-model="approvePeople" readonly>
								<template #append>
									<el-button @click="peopleSearch">查询</el-button>
								</template>
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>	
			</el-form>
			<el-divider content-position="left">申请印章信息</el-divider>
			<el-table ref="sealTable" :data="sealList" stripe border v-if="normalState || pageType != 2">
				<el-table-column label="印章名称" min-width="180" prop="sealName"> </el-table-column>
				<el-table-column label="物料编号" width="150" prop="materialCode"></el-table-column>
				<el-table-column label="规格" width="150" prop="specifications"></el-table-column>
				<el-table-column label="颜色" width="100" prop="sealColor"></el-table-column>
				<el-table-column label="数量" width="90" prop="sealCount"></el-table-column>
				<el-table-column label="印章类型" width="100" prop="sealType"></el-table-column>
				<el-table-column label="印章图样" prop="sealPattern" width="170">
                    <template #default="scope">
                        <bydWaterMark ref="wm" text="印章管理系统" subtext="印章图样">
                           <el-image @click="handleLoad"
                                style="width: 120px; height: 100px" 
                                :preview-teleported="true" 
                                :src="scope.row.sealPattern" 
                                :fit="fit" 
                                :preview-src-list="[scope.row.sealPattern]">
                            </el-image>
                        </bydWaterMark>
                    </template>
                </el-table-column>
				<el-table-column label="备注" width="180" prop="engraveRemark"></el-table-column>
			</el-table>
			<byd-form-table	byd-form-table v-model="sealList"  drag-sort placeholder="请点击左上角加号(+)添加印章数据" style="width: 100%" v-else-if="pageType == 2"> 
				<el-table-column label="印章名称" width="180" prop="sealName"> 
					<template #default="scope">
						<el-input  v-model.trim="scope.row.sealName" placeholder="请输入印章名称"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="物料编号" width="180">
					<template #default="scope">
						<el-input v-model.trim="scope.row.materialCode" placeholder="请输入物料编号"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="规格" width="180">
					<template #default="scope">
						<el-input v-model.trim="scope.row.specifications" placeholder="请输入规格"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="颜色" min-width="120">
					<template #default="scope">
						<el-input v-model.trim="scope.row.sealColor" placeholder="请输入颜色"></el-input>
					</template>
				</el-table-column>
				<el-table-column label="数量" width="105">
					<template #default="scope">
						<el-input-number v-model="scope.row.sealCount" :min="1" style="width: 80px" size="small" />
					</template>
				</el-table-column>
				<el-table-column label="印章类型" width="130">
					<template #default="scope">
						<el-select v-model="scope.row.sealType" placeholder="印章类型">
							<el-option label="实体印章" value="实体印章" />
							<el-option label="电子印章" value="电子印章" />
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="印章图样" width="178">
					<template #default="scope">
						<el-upload
							class="avatar-uploader"
							:show-file-list="false"
							:before-upload="beforeAvatarUpload"
							:on-success="(res, file) => handleAvatarSuccess(res, file, scope)"
							:http-request="request">
							<img v-if="scope.row.$url || scope.row.sealPattern" :src="scope.row.$url || scope.row.sealPattern" class="avatar" />
							<el-icon v-else class="avatar-uploader-icon"><ElIconPlus /></el-icon>
						</el-upload>
					</template>
				</el-table-column>
				<el-table-column label="备注" width="180">
					<template #default="scope">
						<el-input v-model.trim="scope.row.engraveRemark" type="textarea" placeholder="请输入备注"></el-input>
					</template>
				</el-table-column>
			</byd-form-table>
			<el-divider content-position="left">流转信息</el-divider>
			<el-table ref="nodeTable" :data="processNodeList" stripe border>
				<el-table-column label="节点名称" width="180" prop="nodeName"> </el-table-column>
				<el-table-column label="审批人" width="180"  prop="confirmName"></el-table-column>
				<el-table-column label="开始时间" width="180" prop="receiveTime"></el-table-column>
				<el-table-column label="结束时间" width="180" prop="approveTime"></el-table-column>
				<el-table-column label="审批结果" width="120" prop="approveResult"></el-table-column>
				<el-table-column label="审批意见" min-width="180" prop="approveRemark"></el-table-column>
			</el-table>
			<div v-if="pageType == 2">
				<div v-if="normalState">
					<el-divider content-position="left">审批</el-divider>
					<el-row :gutter="0">
						<el-col :span="1">
							<span class="remarkSpan">审批意见:</span>
						</el-col>
						<el-col :span="23">
							<el-input v-model.trim="approveRemark" type="textarea" placeholder="请输入审批意见"></el-input>
						</el-col>
					</el-row>
					<div class="submitBtn">
						<el-button type="primary" @click="agreeProcess" :loading="btnloading">同意</el-button>
						<el-button type="primary" @click="changePeoplePage" :loading="btnloading">转交</el-button>
						<el-button type="danger" @click="rejectProcess" :loading="btnloading">驳回</el-button>
					</div>
				</div>
				<div class="submitBtn" v-else>
					<el-button type="primary" @click="submitAgain" :loading="btnloading">重新提交</el-button>
					<el-button type="danger" @click="stopProcess" :loading="btnloading">废止</el-button>
				</div>
			</div>
			<div v-else-if="pageType == 1 && approveNode == '厂长/经理审批'">
				<div class="submitBtn">
					<el-button type="primary" @click="backProcess" :loading="btnloading">撤回</el-button>
				</div>
			</div>
			<peopleSearch title="人员查询" v-model="searchDialog" @close="changeBtnClose" @selectChange="checkPeople"/>
		</el-card>
	</el-main>
</template>

<script>
	import { Check } from '@element-plus/icons-vue'
	import { create } from '@/utils/watermark'
	import peopleSearch from '@/views/components/peopleSearch.vue'
	export default {
		name: 'processDetail',
		components:{Check,peopleSearch},
		props: {
			trackId: {
				type: String,
				default: ''
			},
			pageType: {
				type: Number,
				default: 1
			}
		},
		data() {
			return {
				basicInfo: {
					topic: "",
					applyTime: '',
					jobNumber: "",
					name: "",
					place: "",
					factory: "",
					department: "",
					email:"",
					applyReason: ""
				},
				processState : 1,
				approveNode : "",
				approvePeople:"",
				searchDialog : false,
				searchDialogState : 1,
				searchJobNumber:"",
				searchUsername:"",
				peopleList:[],
				sealList:[],
				processNodeList:[],
				normalState:true,
				approveRemark:"",
				btnloading : false,
			}
		},
		mounted(){
			this.getProcessInfo();
			this.getApplySealInfo();
			this.getProcessNode();
		},
		methods: {
			//获取流程基本信息
			async getProcessInfo(){
				const trackId = this.trackId;
				var param = {
					trackId : trackId
				}
				var info = await this.$api.process.processDetailInfo.get(param)
				if(info.respCode == "0000"){
					this.basicInfo.topic = info.data.processInfo.processName;
					this.basicInfo.applyTime = info.data.processInfo.applyTime;
					this.basicInfo.jobNumber = info.data.processInfo.applyNumber;
					this.basicInfo.name = info.data.processInfo.applyName;
					this.basicInfo.place = info.data.processInfo.place;
					this.basicInfo.factory = info.data.processInfo.applyFactory;
					this.basicInfo.department = info.data.processInfo.applyDepartment;
					this.basicInfo.email = info.data.processInfo.applyEmail;
					this.basicInfo.applyReason = info.data.processInfo.applyReason;
					this.processState = info.data.processInfo.state;
					this.approveNode = info.data.processInfo.approveNode;
					if(info.data.processInfo.state == "2" || info.data.processInfo.state == '4'){
						this.normalState = false;
						// this.approvePeople = info.data.processInfo.approvePeople;
					}
				}else{
					this.$message.error(info.respDesc)
				}
			},
			//获取印章相关信息
			async getApplySealInfo(){
				const trackId = this.trackId;
				var param = {
					trackId : trackId
				}
				var sealInfo = await this.$api.process.applySealInfo.get(param);
				if(sealInfo.respCode == "0000"){
					this.sealList = sealInfo.data.sealInfo;
				}else{
					this.$message.error(sealInfo.respDesc)
				}
			},
			//添加水印
			handleLoad() {
                setTimeout(() => {
                    const img = document.querySelector('.el-image-viewer__canvas');
                    var userInfo = this.$tool.data.get("USER_INFO");
                    create(img, { text: '印章管理系统',subtext : userInfo.username + userInfo.jobnumber })
                }, 100)
            },
			//获取节点信息
			async getProcessNode(){
				const trackId = this.trackId;
				var param = {
					trackId : trackId
				}
				var nodeInfo = await this.$api.process.processNodeInfo.get(param);
				if(nodeInfo.respCode == "0000"){
					this.processNodeList = nodeInfo.data.processNodeInfo
				}else{
					this.$message.error(nodeInfo.respDesc)
				}
			},
			//同意流程
			async agreeProcess(){
				this.btnloading = true;
				var processParam = {
					place : this.basicInfo.place,
					trackId : this.trackId,
					approveRemark : this.approveRemark
				}
				var agreeResult = await this.$api.process.agreeProcess.post(processParam);
				if(agreeResult.status == 200){
					this.$message({
						message : agreeResult.message,
						type : 'success'
					})
					setTimeout(() => {
						location.reload();
					},1500)
				}else{
					this.$message.error(agreeResult.message);
					this.btnloading = false;
				}
			},
			//驳回流程
			async rejectProcess(){
				this.btnloading = true;
				if(!this.approveRemark){
					this.$message.error("请输入审批意见");
					this.btnloading = false;
					return false;
				}
				var rejectParam = {
					trackId : this.trackId,
					approveRemark : this.approveRemark
				}
				var rejectResult = await this.$api.process.rejectProcess.post(rejectParam);
				if(rejectResult.status == 200){
					this.$message({
						message : rejectResult.message,
						type : 'success'
					})
					setTimeout(() => {
						location.reload();
					},1500)
				}else{
					this.$message.error(rejectResult.message);
					this.btnloading = false;
				}
			},
			//印章图样上传
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
				const isLt2M = file.size / 1024 / 1024 < 5;
				if (!isJPG) {
				this.$message.error('上传头像图片只能是图片格式!');
				}
				if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过5MB!');
				}
				return isJPG && isLt2M;
			},
			handleAvatarSuccess(res, file, scope) {
				if(scope && scope.row) {
					scope.row.$url = URL.createObjectURL(file.raw);
					scope.row.sealPattern = res?.data?.data?.src;
				}
			},
			request(param){
				const data = new FormData();
				var file = param.file
				data.append("file", file);
				this.$api.engrave.myupload.post(data).then(res => {
					param.onSuccess(res)
				}).catch(err => {
					param.onError(err)
				})
			},
			//查找审批人
			peopleSearch(){
				this.searchDialog = true;
			},
			async checkPeople(row = {}){
				const { jobnumber,username } = row;
				if(this.searchDialogState == 2){
					//流程转交
					const changeParam = {
						trackId : this.trackId,
						approveRemark : this.approveRemark,
						changePeople : jobnumber + "-" + username
					}
					var changeResult = await this.$api.process.changeApprove.post(changeParam);
					if(changeResult.status == 200){
						this.$message({
							message : changeResult.message,
							type : 'success'
						})
						setTimeout(() => {
							location.reload();
						},1500)
					}else{
						this.$message.error(changeResult.message)
					}
				}else{
					this.approvePeople = jobnumber + "-" + username;
				}
				this.searchDialogState = 1;
				this.searchDialog = false;
				this.searchJobNumber = "";
				this.searchUsername = "";
				this.peopleList = [];
			},
			//重新提交
			async submitAgain(){
				this.btnloading = true;
				//判断邮箱格式
				if(this.basicInfo.email){
					const emailTest = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
					if(!emailTest.test(this.basicInfo.email)){
						this.$message.error('邮箱格式填写有误!');
						this.btnloading = false;
						return false;
					}
				}
				if(!this.approvePeople){
					this.$message.error('请选择审核人!');
					this.btnloading = false;
					return false;
				}
				if(!this.basicInfo.applyReason){
					this.$message.error('请填写申请原因!');
					this.btnloading = false;
					return false;
				}
				//判断印章信息是否填完备
				var finish = true;
				if(!this.sealList.length > 0){
					this.$message.error('请添加刻制印章信息!');
					this.btnloading = false;
					finish = false;
				}else{
					var notComplete = new Set;
					this.sealList.forEach((item, id) => {
						if(JSON.stringify(item) == "{}"){
							finish = false;
							notComplete.add(id + 1);
						}else{
							const keyList = Object.keys(item);
							const valueList = Object.values(item);
							if(valueList.length != keyList.length || keyList.length<8){
								finish = false;
								notComplete.add(id + 1);
							}else{
								valueList.forEach(function(i){
									if(i == "" || i == null){
										finish = false;
										notComplete.add(id + 1);
										return false;
									}
								})
							}
						}
					})	
				}
				if(!finish){
					this.btnloading = false;
					if(notComplete && notComplete.size > 0){
						let permission = Array.from(notComplete).join(",");
						this.$message.error("请补全第" + permission + "行刻制印章信息")
					}
					this.btnloading = false;
					return false;
				}else{
					var applyResult = await this.$api.process.submitAgain.post({
						trackId : this.trackId,
						applyReason : this.basicInfo.applyReason,
						approvePeople : this.approvePeople,
						sealInfo: JSON.stringify(this.sealList)
					})
					if(applyResult.status == 200){
						this.$message({
							message: applyResult.message,
							type: 'success',
						})
						setTimeout(() => {
							location.reload();
						},1500)
					}else{
						this.btnloading = false;
						this.$message.error(applyResult.message)
					}
				}
			},
			//转交
			changePeoplePage(){
				if(!this.approveRemark){
					this.$message.error("请输入审批意见");
					return false;
				}
				this.searchDialogState = 2;
				this.btnloading = true;
				this.searchDialog = true;
			},
			changeBtnClose(){
				this.btnloading = false;
			},
			//撤回
			async backProcess(){
				this.btnloading = true;
				const backParam = {
					trackId : this.trackId
				}
				var backResult = await this.$api.process.backProcess.post(backParam);
				if(backResult.status == 200){
					this.$message({
						message: backResult.message,
						type: 'success',
					})
					setTimeout(() => {
						location.reload();
					},1500)
				}else{
					this.btnloading = false;
					this.$message.error(backResult.message)
				}
			},
			//流程废止
			async stopProcess(){
				this.btnloading = true;
				const stopParam = {
					trackId : this.trackId
				}
				var stopResult = await this.$api.process.stopProcess.post(stopParam);
				if(stopResult.status == 200){
					this.$message({
						message: stopResult.message,
						type: 'success',
					})
					setTimeout(() => {
						location.reload();
					},1500)
				}else{
					this.btnloading = false;
					this.$message.error(stopResult.message)
				}
			}
		}
	}
</script>

<style>
	.searchDiog{
		padding-top: 20px;
	}
	.remarkSpan{
		font-size: var(--el-form-label-font-size);
    	color: var(--el-text-color-regular);
		font-size: 14px;
	}
	.submitBtn{
		text-align: center;
		padding-top: 20px;
	}
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}
	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 150px;
		height: 150px;
		line-height: 150px;
		text-align: center;
	}
	.avatar {
		width: 150px;
		height: 150px;
		display: block;
	}
	
</style>
